import React, { useState, useEffect } from 'react';
import './Settings.css';

function Settings({ settingsManager, onClose }) {
  const [settings, setSettings] = useState(settingsManager.getAll());
  const [activeTab, setActiveTab] = useState('general');
  const [mediaDevices, setMediaDevices] = useState({
    audioInputs: [],
    audioOutputs: [],
    videoInputs: []
  });
  const [saveStatus, setSaveStatus] = useState('');

  useEffect(() => {
    // 加载媒体设备
    settingsManager.getMediaDevices().then(devices => {
      setMediaDevices(devices);
    });

    // 监听设置变化
    const handleSettingsChanged = (newSettings) => {
      setSettings(newSettings);
    };

    settingsManager.on('settings-changed', handleSettingsChanged);

    return () => {
      settingsManager.off('settings-changed', handleSettingsChanged);
    };
  }, [settingsManager]);

  const handleChange = (key, value) => {
    const newSettings = { ...settings, [key]: value };
    setSettings(newSettings);
  };

  const handleSave = () => {
    if (settingsManager.update(settings)) {
      setSaveStatus('success');
      setTimeout(() => setSaveStatus(''), 2000);
    } else {
      setSaveStatus('error');
      setTimeout(() => setSaveStatus(''), 2000);
    }
  };

  const handleReset = () => {
    if (window.confirm('确定要重置所有设置为默认值吗？')) {
      settingsManager.reset();
      setSettings(settingsManager.getAll());
      setSaveStatus('reset');
      setTimeout(() => setSaveStatus(''), 2000);
    }
  };

  const handleExport = () => {
    settingsManager.exportSettings();
  };

  const handleImport = async (e) => {
    const file = e.target.files?.[0];
    if (file) {
      const success = await settingsManager.importSettings(file);
      if (success) {
        setSettings(settingsManager.getAll());
        setSaveStatus('imported');
        setTimeout(() => setSaveStatus(''), 2000);
      } else {
        setSaveStatus('import-error');
        setTimeout(() => setSaveStatus(''), 2000);
      }
    }
  };

  const renderGeneralSettings = () => (
    <div className="settings-section">
      <h3>常规设置</h3>

      <div className="settings-item">
        <label htmlFor="deviceName">设备名称</label>
        <input
          id="deviceName"
          type="text"
          value={settings.deviceName}
          onChange={(e) => handleChange('deviceName', e.target.value)}
          placeholder="输入设备名称"
        />
        <span className="settings-help">其他用户将看到此名称</span>
      </div>

      <div className="settings-item">
        <label htmlFor="autoConnect">
          <input
            id="autoConnect"
            type="checkbox"
            checked={settings.autoConnect}
            onChange={(e) => handleChange('autoConnect', e.target.checked)}
          />
          自动连接到服务器
        </label>
      </div>

      <div className="settings-item">
        <label htmlFor="language">语言</label>
        <select
          id="language"
          value={settings.language}
          onChange={(e) => handleChange('language', e.target.value)}
        >
          <option value="zh-CN">简体中文</option>
          <option value="en-US">English</option>
        </select>
      </div>
    </div>
  );

  const renderMessageSettings = () => (
    <div className="settings-section">
      <h3>消息设置</h3>

      <div className="settings-item">
        <label htmlFor="messageNotifications">
          <input
            id="messageNotifications"
            type="checkbox"
            checked={settings.messageNotifications}
            onChange={(e) => handleChange('messageNotifications', e.target.checked)}
          />
          启用消息通知
        </label>
      </div>

      <div className="settings-item">
        <label htmlFor="messageSound">
          <input
            id="messageSound"
            type="checkbox"
            checked={settings.messageSound}
            onChange={(e) => handleChange('messageSound', e.target.checked)}
          />
          消息提示音
        </label>
      </div>

      <div className="settings-item">
        <label htmlFor="enterToSend">
          <input
            id="enterToSend"
            type="checkbox"
            checked={settings.enterToSend}
            onChange={(e) => handleChange('enterToSend', e.target.checked)}
          />
          按 Enter 发送消息
        </label>
        <span className="settings-help">禁用后使用 Ctrl+Enter 发送</span>
      </div>

      <div className="settings-item">
        <label htmlFor="showTimestamps">
          <input
            id="showTimestamps"
            type="checkbox"
            checked={settings.showTimestamps}
            onChange={(e) => handleChange('showTimestamps', e.target.checked)}
          />
          显示消息时间戳
        </label>
      </div>

      <div className="settings-item">
        <label htmlFor="messageHistoryLimit">历史消息加载数量</label>
        <input
          id="messageHistoryLimit"
          type="number"
          min="10"
          max="1000"
          value={settings.messageHistoryLimit}
          onChange={(e) => handleChange('messageHistoryLimit', parseInt(e.target.value))}
        />
        <span className="settings-help">每次加载的历史消息数量</span>
      </div>
    </div>
  );

  const renderFileSettings = () => (
    <div className="settings-section">
      <h3>文件传输设置</h3>

      <div className="settings-item">
        <label htmlFor="fileNotifications">
          <input
            id="fileNotifications"
            type="checkbox"
            checked={settings.fileNotifications}
            onChange={(e) => handleChange('fileNotifications', e.target.checked)}
          />
          启用文件传输通知
        </label>
      </div>

      <div className="settings-item">
        <label htmlFor="autoDownload">
          <input
            id="autoDownload"
            type="checkbox"
            checked={settings.autoDownload}
            onChange={(e) => handleChange('autoDownload', e.target.checked)}
          />
          自动下载接收的文件
        </label>
        <span className="settings-help">不建议开启，可能导致存储空间问题</span>
      </div>

      <div className="settings-item">
        <label htmlFor="downloadPath">默认下载路径</label>
        <input
          id="downloadPath"
          type="text"
          value={settings.downloadPath}
          onChange={(e) => handleChange('downloadPath', e.target.value)}
          placeholder="留空使用系统默认路径"
        />
      </div>

      <div className="settings-item">
        <label htmlFor="maxFileSize">最大文件大小 (GB)</label>
        <input
          id="maxFileSize"
          type="number"
          min="1"
          max="100"
          value={settings.maxFileSize}
          onChange={(e) => handleChange('maxFileSize', parseInt(e.target.value))}
        />
        <span className="settings-help">限制可发送的文件大小</span>
      </div>
    </div>
  );

  const renderCallSettings = () => (
    <div className="settings-section">
      <h3>通话设置</h3>

      <div className="settings-item">
        <label htmlFor="callNotifications">
          <input
            id="callNotifications"
            type="checkbox"
            checked={settings.callNotifications}
            onChange={(e) => handleChange('callNotifications', e.target.checked)}
          />
          启用通话通知
        </label>
      </div>

      <div className="settings-item">
        <label htmlFor="callSound">
          <input
            id="callSound"
            type="checkbox"
            checked={settings.callSound}
            onChange={(e) => handleChange('callSound', e.target.checked)}
          />
          来电铃声
        </label>
      </div>

      <div className="settings-item">
        <label htmlFor="videoQuality">视频通话质量</label>
        <select
          id="videoQuality"
          value={settings.videoQuality}
          onChange={(e) => handleChange('videoQuality', e.target.value)}
        >
          <option value="sd">标清 (480p)</option>
          <option value="hd">高清 (720p)</option>
          <option value="fhd">全高清 (1080p)</option>
        </select>
      </div>

      <div className="settings-item">
        <label htmlFor="audioInput">麦克风</label>
        <select
          id="audioInput"
          value={settings.audioInput}
          onChange={(e) => handleChange('audioInput', e.target.value)}
        >
          <option value="default">系统默认</option>
          {mediaDevices.audioInputs.map(device => (
            <option key={device.deviceId} value={device.deviceId}>
              {device.label || `麦克风 ${device.deviceId.slice(0, 8)}`}
            </option>
          ))}
        </select>
      </div>

      <div className="settings-item">
        <label htmlFor="audioOutput">扬声器</label>
        <select
          id="audioOutput"
          value={settings.audioOutput}
          onChange={(e) => handleChange('audioOutput', e.target.value)}
        >
          <option value="default">系统默认</option>
          {mediaDevices.audioOutputs.map(device => (
            <option key={device.deviceId} value={device.deviceId}>
              {device.label || `扬声器 ${device.deviceId.slice(0, 8)}`}
            </option>
          ))}
        </select>
      </div>

      <div className="settings-item">
        <label htmlFor="videoInput">摄像头</label>
        <select
          id="videoInput"
          value={settings.videoInput}
          onChange={(e) => handleChange('videoInput', e.target.value)}
        >
          <option value="default">系统默认</option>
          {mediaDevices.videoInputs.map(device => (
            <option key={device.deviceId} value={device.deviceId}>
              {device.label || `摄像头 ${device.deviceId.slice(0, 8)}`}
            </option>
          ))}
        </select>
      </div>

      <div className="settings-item">
        <label htmlFor="echoCancellation">
          <input
            id="echoCancellation"
            type="checkbox"
            checked={settings.echoCancellation}
            onChange={(e) => handleChange('echoCancellation', e.target.checked)}
          />
          回声消除
        </label>
      </div>

      <div className="settings-item">
        <label htmlFor="noiseSuppression">
          <input
            id="noiseSuppression"
            type="checkbox"
            checked={settings.noiseSuppression}
            onChange={(e) => handleChange('noiseSuppression', e.target.checked)}
          />
          噪音抑制
        </label>
      </div>

      <div className="settings-item">
        <label htmlFor="autoGainControl">
          <input
            id="autoGainControl"
            type="checkbox"
            checked={settings.autoGainControl}
            onChange={(e) => handleChange('autoGainControl', e.target.checked)}
          />
          自动增益控制
        </label>
      </div>
    </div>
  );

  const renderAppearanceSettings = () => (
    <div className="settings-section">
      <h3>界面设置</h3>

      <div className="settings-item">
        <label htmlFor="theme">主题</label>
        <select
          id="theme"
          value={settings.theme}
          onChange={(e) => handleChange('theme', e.target.value)}
        >
          <option value="light">浅色</option>
          <option value="dark">深色</option>
        </select>
      </div>

      <div className="settings-item">
        <label htmlFor="fontSize">字体大小</label>
        <select
          id="fontSize"
          value={settings.fontSize}
          onChange={(e) => handleChange('fontSize', e.target.value)}
        >
          <option value="small">小</option>
          <option value="medium">中</option>
          <option value="large">大</option>
        </select>
      </div>

      <div className="settings-item">
        <label htmlFor="compactMode">
          <input
            id="compactMode"
            type="checkbox"
            checked={settings.compactMode}
            onChange={(e) => handleChange('compactMode', e.target.checked)}
          />
          紧凑模式
        </label>
        <span className="settings-help">减少界面元素间距</span>
      </div>
    </div>
  );

  const renderPrivacySettings = () => (
    <div className="settings-section">
      <h3>隐私设置</h3>

      <div className="settings-item">
        <label htmlFor="readReceipts">
          <input
            id="readReceipts"
            type="checkbox"
            checked={settings.readReceipts}
            onChange={(e) => handleChange('readReceipts', e.target.checked)}
          />
          发送已读回执
        </label>
        <span className="settings-help">让对方知道你已阅读消息</span>
      </div>

      <div className="settings-item">
        <label htmlFor="typingIndicators">
          <input
            id="typingIndicators"
            type="checkbox"
            checked={settings.typingIndicators}
            onChange={(e) => handleChange('typingIndicators', e.target.checked)}
          />
          显示正在输入状态
        </label>
      </div>

      <div className="settings-item">
        <label htmlFor="lastSeenStatus">
          <input
            id="lastSeenStatus"
            type="checkbox"
            checked={settings.lastSeenStatus}
            onChange={(e) => handleChange('lastSeenStatus', e.target.checked)}
          />
          显示最后在线时间
        </label>
      </div>
    </div>
  );

  const renderAdvancedSettings = () => (
    <div className="settings-section">
      <h3>高级设置</h3>

      <div className="settings-item">
        <label htmlFor="reconnectAttempts">最大重连次数</label>
        <input
          id="reconnectAttempts"
          type="number"
          min="1"
          max="50"
          value={settings.reconnectAttempts}
          onChange={(e) => handleChange('reconnectAttempts', parseInt(e.target.value))}
        />
      </div>

      <div className="settings-item">
        <label htmlFor="heartbeatInterval">心跳间隔 (毫秒)</label>
        <input
          id="heartbeatInterval"
          type="number"
          min="5000"
          max="120000"
          step="1000"
          value={settings.heartbeatInterval}
          onChange={(e) => handleChange('heartbeatInterval', parseInt(e.target.value))}
        />
        <span className="settings-help">保持连接活跃的心跳间隔</span>
      </div>

      <div className="settings-item">
        <label htmlFor="discoveryTimeout">服务发现超时 (毫秒)</label>
        <input
          id="discoveryTimeout"
          type="number"
          min="3000"
          max="30000"
          step="1000"
          value={settings.discoveryTimeout}
          onChange={(e) => handleChange('discoveryTimeout', parseInt(e.target.value))}
        />
      </div>

      <div className="settings-item">
        <label htmlFor="callTimeout">来电超时 (毫秒)</label>
        <input
          id="callTimeout"
          type="number"
          min="10000"
          max="300000"
          step="1000"
          value={settings.callTimeout}
          onChange={(e) => handleChange('callTimeout', parseInt(e.target.value))}
        />
        <span className="settings-help">无应答自动挂断时间</span>
      </div>
    </div>
  );

  return (
    <div className="settings-modal">
      <div className="settings-container">
        <div className="settings-header">
          <h2>设置</h2>
          <button className="close-btn" onClick={onClose}>×</button>
        </div>

        <div className="settings-content">
          <div className="settings-sidebar">
            <button
              className={activeTab === 'general' ? 'active' : ''}
              onClick={() => setActiveTab('general')}
            >
              常规
            </button>
            <button
              className={activeTab === 'messages' ? 'active' : ''}
              onClick={() => setActiveTab('messages')}
            >
              消息
            </button>
            <button
              className={activeTab === 'files' ? 'active' : ''}
              onClick={() => setActiveTab('files')}
            >
              文件传输
            </button>
            <button
              className={activeTab === 'calls' ? 'active' : ''}
              onClick={() => setActiveTab('calls')}
            >
              通话
            </button>
            <button
              className={activeTab === 'appearance' ? 'active' : ''}
              onClick={() => setActiveTab('appearance')}
            >
              界面
            </button>
            <button
              className={activeTab === 'privacy' ? 'active' : ''}
              onClick={() => setActiveTab('privacy')}
            >
              隐私
            </button>
            <button
              className={activeTab === 'advanced' ? 'active' : ''}
              onClick={() => setActiveTab('advanced')}
            >
              高级
            </button>
          </div>

          <div className="settings-main">
            {activeTab === 'general' && renderGeneralSettings()}
            {activeTab === 'messages' && renderMessageSettings()}
            {activeTab === 'files' && renderFileSettings()}
            {activeTab === 'calls' && renderCallSettings()}
            {activeTab === 'appearance' && renderAppearanceSettings()}
            {activeTab === 'privacy' && renderPrivacySettings()}
            {activeTab === 'advanced' && renderAdvancedSettings()}

            <div className="settings-actions">
              <div className="settings-left-actions">
                <button className="secondary-btn" onClick={handleExport}>
                  导出设置
                </button>
                <label className="import-btn secondary-btn">
                  导入设置
                  <input
                    type="file"
                    accept=".json"
                    onChange={handleImport}
                    style={{ display: 'none' }}
                  />
                </label>
              </div>
              <div className="settings-right-actions">
                <button className="danger-btn" onClick={handleReset}>
                  重置为默认
                </button>
                <button className="primary-btn" onClick={handleSave}>
                  保存设置
                </button>
              </div>
            </div>

            {saveStatus && (
              <div className={`save-status ${saveStatus}`}>
                {saveStatus === 'success' && '设置已保存'}
                {saveStatus === 'error' && '保存失败，请重试'}
                {saveStatus === 'reset' && '已重置为默认设置'}
                {saveStatus === 'imported' && '设置导入成功'}
                {saveStatus === 'import-error' && '导入失败，请检查文件格式'}
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}

export default Settings;
